﻿using System;
using System.Linq;
using System.Net;
using Google.Apis.Customsearch.v1;
using Google.Apis.Customsearch.v1.Data;
using BotDetector.Core.Utilities;

namespace WebBotDetector.WebModule
{
    public class WebSearchUtility
    {
        private string ROOT_URI_BING = Constants.RootUriBing;
        private string API_KEY_BING = Constants.ApiKeyBing;
        private string API_KEY_GOOGLE = Constants.ApiKeyGoogle;
        private string SEARCH_ENGINE_ID_GOOGLE = Constants.SearchEngineIdGoogle;

        public long GetBingTotalResults(String queryString, Boolean exactResults)
        {
            var bingContainer = new Bing.BingSearchContainer(new Uri(ROOT_URI_BING));
            bingContainer.Credentials = new NetworkCredential(API_KEY_BING, API_KEY_BING);

            String processedQueryString = queryString;
            if (exactResults)
                queryString = "\"" + queryString + "\"";

            var query = bingContainer.Composite("web", processedQueryString,null, null, null, null, null, null, null, null, null, null, null, null, null);
            var results = query.Execute();

            var totalResults = results.First().WebTotal;

            return totalResults == null ? 0 : totalResults.Value;
        }

        public long GetGoogleTotalResults(String queryString, Boolean exactResults)
        {
            CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = API_KEY_GOOGLE });

            String processedQueryString = queryString;
            if (exactResults)
                processedQueryString = "\"" + queryString + "\"";

            Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = customSearchService.Cse.List(processedQueryString);
            listRequest.Cx = SEARCH_ENGINE_ID_GOOGLE;
            Search results = listRequest.Execute();
            
            long? totalResults = results.SearchInformation.TotalResults;
            
            return totalResults == null ? 0 : totalResults.Value;
        }
    }
}
